package com.chenfwind.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.BindException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


@Controller
@RequestMapping("/file")
public class FileController {
	/**
	 * logger.
	 */
	private final Logger logger = Logger.getLogger(FileController.class);

	public String fileSuffix(String filename) {
		if (StringUtils.isBlank(filename) || filename.indexOf(".") == -1) {
			return "";
		} else {
			return filename.substring(filename.lastIndexOf(".") + 1);
		}
	}

	/**
	 * 
	 * downloadFile 方法描述：文件下载接口
	 * 
	 * @author 吴雪婷
	 * @最后修改人： 吴雪婷
	 * @最后修改日期： 2015-7-6 下午4:41:50
	 * @version 0.4
	 * 
	 * @param session
	 * @param fileName
	 * @param uid
	 * @param request
	 * @param response
	 * @throws Exception
	 * @return void
	 */
	@RequestMapping("/{uid}/download")
	public void downloadFile(HttpSession session, String fileName, @PathVariable String uid, HttpServletRequest request, HttpServletResponse response) throws Exception {

		String fileNameStr = URLEncoder.encode(fileName, "UTF-8");
		if (fileName.length() > 150) {
			String guessCharset = "gb2312";
			fileNameStr = new String(fileName.getBytes(guessCharset), "ISO8859-1");
		}
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		response.setHeader("Content-Disposition", "attachment;fileName=" + fileNameStr);
		// 禁止缓存
		response.setHeader("Cache-Control", "no-store");
		response.setHeader("Accept-Ranges", "bytes");
		response.setHeader("Pragrma", "no-cache");
		response.setDateHeader("Expires", 0);

		// 链接来源地址
		String referer = request.getHeader("referer");
		System.out.println("refer is " + referer);
		// if (referer == null || !referer.contains(request.getServerName())) {
		// 防盗链
		// return null;
		// }
		// 断点续传
		Long pos = (long) 0;
		logger.debug(fileName + " request.getHeader(Range)" + request.getHeader("Range"));
		if (null != request.getHeader("Range")) {
			response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
			try {
				pos = Long.parseLong(request.getHeader("Range").replaceAll("bytes=", "").replaceAll("-", ""));
			} catch (NumberFormatException e) {
				pos = (long) 0;
			}
		}

		OutputStream os = null;
		InputStream inputStream = null;
		try {
			// 服务器端获取
			String uploadRoot = session.getServletContext().getRealPath("");
			String realPath = uploadRoot.substring(0, com.chenfwind.common.StringUtils.findLastSlash(uploadRoot)) + fileName;
			File downFile = new File(realPath);
			if (!downFile.exists())
				return;

			inputStream = new FileInputStream(downFile);
			response.setContentLength((int) downFile.length());
			response.setDateHeader("Last-Modified", downFile.lastModified());
			response.setDateHeader("Last-Modified", downFile.lastModified());

			String contentRange = new StringBuffer("bytes ").append(pos + "").append("-").append((downFile.length() - 1) + "").append("/").append(downFile.length() + "")
					.toString();
			response.setHeader("Content-Range", contentRange);
			logger.debug(fileName + " Content-Range:" + contentRange);

			os = response.getOutputStream();
			byte[] b = new byte[2048];
			int length;
			Long leftSize = downFile.length() - pos;
			while ((length = inputStream.read(b)) > 0) {
				os.write(b, 0, length);
			}
			
			os.close();
			inputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		} finally {
			if (os != null) {
				os.close();
			}
			if (inputStream != null) {
				inputStream.close();
			}
		}
	}

}
